package com.lingshi.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.shopping.entity.Admin;
import com.lingshi.shopping.entity.AdminRole;
import com.lingshi.shopping.entity.Permission;
import com.lingshi.shopping.exception.BusException;
import com.lingshi.shopping.service.AdminService;
import com.lingshi.shopping_admin_service.mapper.AdminMapper;
import com.lingshi.shopping_admin_service.mapper.AdminRoleMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


@DubboService
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    @Override
    @Transactional
    public void delete(Long aid) {

        //删除管理员角色中间表的信息
        LambdaUpdateWrapper<AdminRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdminRole::getAid,aid);
        adminRoleMapper.delete(updateWrapper);
        //删除管理员
        adminMapper.deleteById(aid);
    }

    @Override
    public Admin findById(Long aid) {
        return adminMapper.selectByPrimaryKey(aid);
    }

    @Override
    public Page<Admin> search(int page, int size) {
        Page<Admin> pages = new Page<>(page, size);
        adminMapper.selectPage(pages, null);

        return pages;
    }

    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {
        /**
         * 分配（修改）角色 思路
         * 1，删除之前的所有角色
         * 2，添加新的角色
         */
        LambdaUpdateWrapper<AdminRole> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AdminRole::getAid,aid);
        adminRoleMapper.delete(wrapper);

        //创建新的管理员角色对象
        for (Long rid : rids) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAid(aid);
            adminRole.setRid(rid);
            adminRoleMapper.insert(adminRole);
        }

    }

    @Override
    public Admin findByAdminName(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username);

        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public List<Permission> findAllPermission(String username) {
        List<Permission> permissions =  adminMapper.selectAllPermissions(username);
        return permissions;
    }
}
